var Mongoose = require('mongoose');
var _ = require('lodash');

var keyWordSchema = Mongoose.Schema({
    content: {
        type: String,
        default: ''
    },
    count: {
        type: Number,
        default: 1
    },
    user: [{
        count: {type: Number, default: 1}
    }]
}, {timestamps: true, usePushEach: true});

var KeyWord = Mongoose.model('Keyword', keyWordSchema);

KeyWord.findAndCreate = function (newkeyWord, userId, callback) {

    KeyWord.findOne({content: newkeyWord.content}, function (err, oldKeyWord) {
        console.log(oldKeyWord)
        if (oldKeyWord) {
            oldKeyWord.count++;
            var userExist = false;
            for (var i = 0; i < oldKeyWord.user.length; i++) {
                if (oldKeyWord.user[i]._id.equals(userId)) {
                    userExist = true;
                    break;
                }
            }
            if (userExist) {
                oldKeyWord.user[i].count++;
            } else {
                oldKeyWord.user.push(userId);
            }

            console.log("******")

            oldKeyWord.save(callback);
        } else {
            newkeyWord.save(callback);
        }
    });
};

KeyWord.findKeywordsByWords = function (words, callback) {
    var searchMatch = {};
    var wordsReg = [];
    var sortParameter = 'count',
        sortOrder = -1,
        sort = {};
    sort[sortParameter] = sortOrder;

    if (words) {

        searchMatch = {content: {$in: words}};


        KeyWord.aggregate([
            {"$match": searchMatch},
            {"$sort": sort},
            {
                "$project": {
                    "_id": "$_id",
                    "content": "$content",
                    "count": "$count",
                }
            }
        ], callback);


        /*KeyWord.aggregate([
            {"$match": searchMatch},
            {"$sort": sort},
            {
                "$project": {
                    "_id": "$_id",
                    "updatedAt": "$updatedAt",
                    "createdAt": "$createdAt",
                    "content": "$content",
                    "count": "$count",
                    "user": "$user"
                }
            },
            {
                $unwind: "$user"
            },
            {
                "$project": {
                    "_id": "$_id",
                    "updatedAt": "$updatedAt",
                    "createdAt": "$createdAt",
                    "content": "$content",
                    "count": "$count",
                    "user": "$user._id"
                }
            },
            {
                $lookup: {
                    "from": "users",
                    "localField": "user",
                    "foreignField": "_id",
                    "as": "users"
                }
            }, {
                $unwind: "$users"
            },
            {
                "$project": {
                    "_id": "$_id",
                    "updatedAt": "$updatedAt",
                    "createdAt": "$createdAt",
                    "content": "$content",
                    "count": "$count",
                    "user": "$user._id",
                    "name": "$users.firstName"
                }
            }
        ], callback);*/
    }
};

KeyWord.getWordCloud = function (params, callback) {
    var sortParameter = params.sortParameter || 'count',
        sortOrder = -1,
        sort = {};
    sort[sortParameter] = sortOrder;
    KeyWord.aggregate([
        {"$sort": sort},
        {"$limit": 1000}
    ], callback);
};

KeyWord.getUserKeywords = function (userId, callback) {
    var searchMatch = {user: {$elemMatch: {_id: Mongoose.Types.ObjectId(userId)}}};
    KeyWord.aggregate([
        {$match: searchMatch},
        {
            $project: {
                "content": "$content",
                "user": {
                    $filter: {
                        input: "$user",
                        as: "num",
                        cond: {$eq: ['$$num._id', Mongoose.Types.ObjectId(userId)]}
                    }
                }
            }
        },
        {
            $unwind: "$user"
        },
        {
            $project: {
                "content": "$content",
                "count": "$user.count"
            }
        }
    ], callback);
};

KeyWord.getMatchingKeywords = function (word, callback) {
    KeyWord.aggregate([
        {
            $match: {content: word}
        },
        {
            "$project": {
                "_id": "$_id",
                "updatedAt": "$updatedAt",
                "createdAt": "$createdAt",
                "content": "$content",
                "count": "$count",
                "user": "$user"
            }
        },
        {
            $unwind: "$user"
        },
        {
            "$project": {
                "_id": "$_id",
                "updatedAt": "$updatedAt",
                "createdAt": "$createdAt",
                "content": "$content",
                "count": "$count",
                "user": "$user._id"
            }
        },
        {
            $lookup: {
                "from": "users",
                "localField": "user",
                "foreignField": "_id",
                "as": "users"
            }
        }, {
            $unwind: "$users"
        },
        {
            "$project": {
                "_id": "$_id",
                "updatedAt": "$updatedAt",
                "createdAt": "$createdAt",
                "content": "$content",
                "count": "$count",
                "user": "$user._id",
                "name": "$users.firstName"
            }
        }
    ], callback);
};


KeyWord.getKeyWordCount = function (word, callback) {
    KeyWord.findOne([
        {
            $match: {content: word}
        },
        {
            "$project": {
                "_id": "$_id",
                "updatedAt": "$updatedAt",
                "createdAt": "$createdAt",
                "content": "$content",
                "count": "$count",
                "user": "$user"
            }
        },
        {
            $unwind: "$user"
        },
        {
            "$project": {
                "_id": "$_id",
                "updatedAt": "$updatedAt",
                "createdAt": "$createdAt",
                "content": "$content",
                "count": "$count",
                "user": "$user._id"
            }
        },
        {
            $lookup: {
                "from": "users",
                "localField": "user",
                "foreignField": "_id",
                "as": "users"
            }
        }, {
            $unwind: "$users"
        },
        {
            "$project": {
                "_id": "$_id",
                "updatedAt": "$updatedAt",
                "createdAt": "$createdAt",
                "content": "$content",
                "count": "$count",
                "user": "$user._id",
                "name": "$users.firstName"
            }
        }
    ], callback);
};

KeyWord.getKeyWordCountGT = function (word, callback) {
    return KeyWord.find().count();
};

KeyWord.getKeyWordArea = function (word, callback) {
    KeyWord.aggregate([
        {
            "$group" : {
                "_id" : "$count"
            }
        },
        {
            "$sort" : {
                "_id" : -1.0
            }
        }
    ], callback);
};

KeyWord.getKeyWordCountPercent = function (word, callback) {
    KeyWord.aggregate([
        {
            "$match" : {
                "content" : word
            }
        },
        {
            "$unwind" : {
                "path" : "$user"
            }
        },
        {
            "$group" : {
                "_id" : "_id",
                "total" : {
                    "$sum" : 1
                }
            }
        }
    ], callback);
};

KeyWord.getTotalKeywordCount = function () {
    return KeyWord.find().count();
};





module.exports = KeyWord;